//
//  EFAAnnotationView.m
//  efairy
//
//  Created by XiangDongMBP on 2017/7/29.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAAnnotationView.h"
#import "EFACalloutView.h"

@interface EFAAnnotationView ()<EFACalloutViewDelegate>
@property (nonatomic, strong) EFACalloutView *calloutView;
@end

@implementation EFAAnnotationView

- (void)setSelected:(BOOL)selected animated:(BOOL)animated {
    if (self.selected == selected) {
        return;
    }
    
    if (selected) {
        self.calloutView.titleLabel.text = self.annotation.title;
        self.calloutView.subtitleLabel.text = self.annotation.subtitle;
        CGSize size = [self.calloutView.titleLabel sizeThatFits:CGSizeMake(CGFLOAT_MAX, 20)];
        CGSize subSize = [self.calloutView.subtitleLabel sizeThatFits:CGSizeMake(CGFLOAT_MAX, 20)];
        CGFloat labelWidth = MAX(size.width, subSize.width);
        self.calloutView.frame = CGRectMake(0, 0, labelWidth + 20 + 25, 35);
        self.calloutView.center = CGPointMake(CGRectGetWidth(self.bounds) / 2.f + self.calloutOffset.x,
                                              - CGRectGetHeight(self.calloutView.bounds) / 2.f + self.calloutOffset.y);
        [self addSubview:self.calloutView];
    } else {
        [self.calloutView removeFromSuperview];
    }
    
    [super setSelected:selected animated:animated];
}

#pragma mark - EFACalloutViewDelegate
- (void)calloutView:(EFACalloutView *)calloutView tapGestureTapped:(UITapGestureRecognizer *)gesture {
    if ([self.delegate respondsToSelector:@selector(tappedForAnnotationView:)]) {
        [self.delegate tappedForAnnotationView:self];
    }
}
- (void)calloutView:(EFACalloutView *)calloutView naviTapGestureTapped:(UITapGestureRecognizer *)gesture {
    if ([self.delegate respondsToSelector:@selector(annotationView:naviTapped:)]) {
        [self.delegate annotationView:self naviTapped:gesture.view];
    }
}

#pragma mark - private methods
- (UIView *)hitTest:(CGPoint)point withEvent:(UIEvent *)event {
    UIView *view = [super hitTest:point withEvent:event];
    if (view == nil) {
        CGPoint tempoint = [self.calloutView.titleBgView convertPoint:point fromView:self];
        if (CGRectContainsPoint(self.calloutView.titleBgView.bounds, tempoint)) {
            return self.calloutView.titleBgView;
        }
        
        tempoint = [self.calloutView.naviImgView convertPoint:point fromView:self];
        if (CGRectContainsPoint(self.calloutView.naviImgView.bounds, tempoint)) {
            return self.calloutView.naviImgView;
        }
    }
    return view;
}

#pragma mark - setters and getters
- (EFACalloutView *)calloutView {
    if (!_calloutView) {
        _calloutView = [[EFACalloutView alloc] init];
        _calloutView.delegate = self;
    }
    return _calloutView;
}

@end
